package com.jfinal.ext.config;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.function.Function;

/**
 * @author Timor
 * @version 1.0
 * @date 2022/11/21 16:46:13
 */
public class FileConfigProvider implements IFileConfigProvider {
    private final Function<String, File> fileGetter;

    public FileConfigProvider(@NotNull Function<String, File> fileGetter) {
        this.fileGetter = fileGetter;
    }

    @Override
    public File getFile(@NotNull String name) {
        return fileGetter.apply(name);
    }

    @Override
    public String get(@NotNull String name) throws IOException {
        return FileUtil.readFileToString(getFile(name));
    }

    @Override
    public boolean save(@NotNull String name, @NotNull String config) {
        boolean success;

        final File tempFile = getTempFile(name);

        try {
            FileUtil.writeStringToFile(tempFile, config);

            final File file = getFile(name);

            success = Files.deleteIfExists(file.toPath()) && tempFile.renameTo(file);
        } catch (IOException ignored) {
            tempFile.deleteOnExit();

            success = false;
        }
        return success;
    }

}

class FileUtil {

    public static String readFileToString(File file) throws IOException {
        return Files.readString(file.toPath());
    }

    public static void writeStringToFile(File file, String str) throws IOException {
        Files.writeString(file.toPath(), str);
    }

}